<template>
  <view class="flex-col">

    <view :class="boole?'bottom115':''">
      <!--基础信息-->
      <basic-info v-model="detailForm" :boole="boole" ref="refBasicInfo"/>
      <!--维修信息-->
      <repair-info v-model="detailForm" :boole="boole" :options="options" ref="refRepairInfo"/>

      <!-- 维修项目明细 -->
      <view class="item-wrap" style="margin-bottom: 0" v-if="Number(detailForm.maintenanceType) === 2">
        <view class="lineBottom10">
          <uni-section title="维修项目明细" type="line"/>
        </view>

        <view style="margin: 8rpx 20rpx 30rpx 20rpx">
          <uni-forms ref="detailForm" :model="detailForm" :label-position="boole ? 'top' : 'left'" labelWidth="auto">

            <view v-for="(item,index) in detailForm.carMaintenanceProjectList" :key="index">

              <view style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 20rpx"
                    v-if="boole">
                <text>{{ `维修项目明细表${index + 1}` }}</text>
                <button class="uni-button" size="mini" @click="delDecoration(item, index )" type="warn">删除
                </button>
              </view>

              <uni-forms-item label="维修项目名称:" :key="index" :required="boole"
                              :name="'carMaintenanceProjectList.'+index+'.maintenanceName'"
                              :rules="[{required: true,errorMessage: '维修项目名称'}]">
                <text :class="'maintenanceName'+index"/>
                <uni-easyinput v-if="boole" v-model="item.maintenanceName" placeholder="请输入维修项目名称"/>
                <text v-else> {{ item.maintenanceName || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="金额/元:" :key="index">
                <text> {{ handlePice(item, index) || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="单价材料费:" :key="index" :required="boole"
                              :name="'carMaintenanceProjectList.'+index+'.materialCost'"
                              :rules="[{required: true,errorMessage: '单价材料费'}]">
                <text :class="'materialCost'+index"/>
                <uni-easyinput v-if="boole" v-model="item.materialCost" @clear="clear( item,'materialCost')"
                               @blur="blurTable( item,'materialCost')"
                               placeholder="请输入单价材料费"/>
                <text v-else> {{ item.materialCost || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="数量:" :key="index" :required="boole"
                              :name="'carMaintenanceProjectList.'+index+'.maintNum'"
                              :rules="[{required: true,errorMessage: '数量'}]">
                <text :class="'maintNum'+index"/>
                <uni-easyinput v-if="boole" v-model="item.maintNum"
                               @clear="clear( item,'maintNum')" @blur="blurTable( item,'maintNum')"
                               placeholder="请输入数量"/>
                <text v-else> {{ item.maintNum || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="单价工时费:" :key="index" :required="boole"
                              :name="'carMaintenanceProjectList.'+index+'.laborCost'"
                              :rules="[{required: true,errorMessage: '单价工时费'}]">
                <text :class="'laborCost'+index"/>
                <uni-easyinput v-if="boole" v-model="item.laborCost"
                               @clear="clear( item,'laborCost')" @blur="blurTable( item,'laborCost')"
                               placeholder="请输入单价工时费"/>
                <text v-else> {{ item.laborCost || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="配件号:" :key="index">
                <uni-easyinput v-if="boole" v-model="item.partNumber" placeholder="请输入配件号"/>
                <text v-else> {{ item.partNumber || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="品牌:" :key="index">
                <uni-easyinput v-if="boole" v-model="item.maintBrand" placeholder="请输入品牌"/>
                <text v-else> {{ item.maintBrand || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="型号:" :key="index">
                <uni-easyinput v-if="boole" v-model="item.maintModel" placeholder="请输入型号"/>
                <text v-else> {{ item.maintModel || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="详细信息:" :key="index">
                <uni-easyinput v-if="boole" v-model="item.detailedInfo" placeholder="请输入详细信息"/>
                <text v-else> {{ item.detailedInfo || '-' }}</text>
              </uni-forms-item>

            </view>

            <view style="display: flex;justify-content: center;align-items: center;margin-bottom: 20rpx" v-if="boole">
              <button class="uni-button add-button" size="mini" type="primary" @click="addDecoration">
                添加
              </button>
            </view>

            <uni-forms-item label="上传附件:" :key="index">
              <image-common :disabled="!boole" :up-type="2" v-model="detailForm.maintenanceProjectUrl"/>
            </uni-forms-item>

          </uni-forms>
        </view>
      </view>

      <!--保险公司定损额（车）-->
      <insurance-amount v-model="detailForm" v-if="Number(detailForm.maintenanceType) === 1" :boole="boole"
                        ref="refInsuranceAmount"/>

      <!--主车定损*-->
      <master-car v-model="detailForm" v-if="Number(detailForm.maintenanceType) === 3" :boole="boole" :options="options"
                  :depreciationList="depreciationList" ref="refMasterCar"/>

      <!--保险公司定损额（三者）-->
      <view class="item-wrap" style="margin-bottom: 0" v-if="Number(detailForm.maintenanceType) !== 2">
        <view class="lineBottom10">
          <uni-section title="保险公司定损额（三者）" type="line"/>
        </view>

        <view style="margin: 8rpx 20rpx 30rpx 20rpx">
          <uni-forms ref="detailForm" :model="detailForm" :label-position="boole ? 'top' : 'left'" labelWidth="auto">

            <view v-for="(item,index) in detailForm.threeLossAssessmentDtoList" :key="index">

              <view style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 20rpx"
                    v-if="detailForm.threeLossAssessmentDtoList.length > 1 && boole">
                <text>{{ `保险公司定损额(三者)表${index + 1}` }}</text>
                <button class="uni-button" size="mini" @click="delThreeLoss(item, index )" type="warn">删除
                </button>
              </view>

              <uni-forms-item label="人伤金额:" :key="index"
                              v-if="requiredTable(detailForm.responsibilityType,detailForm.accidentType)"
                              :required="true" :name="'threeLossAssessmentDtoList.'+index+'.personPrice'"
                              :rules="[{required: true, errorMessage: '请输入人伤金额'}]">
                <text :class="'personPrice'+index"/>
                <uni-easyinput v-if="boole" v-model="item.personPrice"
                               @blur="blurTable( item,'personPrice')"
                               placeholder="请输入人伤金额"/>
                <text v-else> {{ item.personPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="人伤金额:" v-else>
                <uni-easyinput v-if="boole" v-model="item.personPrice"
                               @blur="blurTable( item,'personPrice')"
                               placeholder="请输入人伤金额"/>
                <text v-else> {{ item.personPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="施救费用:" :key="index"
                              v-if="requiredTable(detailForm.responsibilityType,detailForm.accidentType)"
                              :required="true" :name="'threeLossAssessmentDtoList.'+index+'.rescueCost'"
                              :rules="[{required: true, errorMessage: '请输入施救费用'}]">
                <text :class="'rescueCost'+index"/>
                <uni-easyinput v-if="boole" v-model="item.rescueCost"
                               @blur="blurTable( item,'rescueCost')" placeholder="请输入施救费用"/>
                <text v-else> {{ item.rescueCost || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="施救费用:" v-else>
                <uni-easyinput v-if="boole" v-model="item.rescueCost"
                               @blur="blurTable( item,'rescueCost')" placeholder="请输入施救费用"/>
                <text v-else> {{ item.rescueCost || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="物损金额:" :key="index"
                              v-if="requiredTable(detailForm.responsibilityType,detailForm.accidentType)"
                              :required="true" :name="'threeLossAssessmentDtoList.'+index+'.damagePrice'"
                              :rules="[{required: true, errorMessage: '请输入物损金额'}]">
                <text :class="'damagePrice'+index"/>
                <uni-easyinput v-if="boole" v-model="item.damagePrice"
                               @blur="blurTable( item,'damagePrice')"
                               placeholder="请输入物损金额"/>
                <text v-else> {{ item.damagePrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="物损金额:" v-else>
                <uni-easyinput v-if="boole" v-model="item.damagePrice"
                               @blur="blurTable( item,'damagePrice')"
                               placeholder="请输入物损金额"/>
                <text v-else> {{ item.damagePrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="三者定损金额:" :key="index"
                              v-if="requiredTable(detailForm.responsibilityType,detailForm.accidentType)"
                              :required="true" :name="'threeLossAssessmentDtoList.'+index+'.otherAssessmentPrice'"
                              :rules="[{required: true, errorMessage: '请输入三者定损金额'}]">
                <text :class="'otherAssessmentPrice'+index"/>
                <uni-easyinput v-if="boole" v-model="item.otherAssessmentPrice"
                               @blur="blurTable( item,'otherAssessmentPrice')"
                               placeholder="请输入三者定损金额"/>
                <text v-else> {{ item.otherAssessmentPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="三者定损金额:" v-else>
                <uni-easyinput v-if="boole" v-model="item.otherAssessmentPrice"
                               @blur="blurTable( item,'otherAssessmentPrice')"
                               placeholder="请输入三者定损金额"/>
                <text v-else> {{ item.otherAssessmentPrice || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="三者车牌号:" :key="index"
                              v-if="requiredTable(detailForm.responsibilityType,detailForm.accidentType)"
                              :required="true" :name="'threeLossAssessmentDtoList.'+index+'.otherCarNo'"
                              :rules="[{required: true, errorMessage: '请输入三者车牌号'}]">
                <text :class="'otherCarNo'+index"/>
                <uni-easyinput v-if="boole" v-model="item.otherCarNo" placeholder="请输入三者车牌号"/>
                <text v-else> {{ item.otherCarNo || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="三者车牌号:" v-else>
                <uni-easyinput v-if="boole" v-model="item.otherCarNo" placeholder="请输入三者车牌号"/>
                <text v-else> {{ item.otherCarNo || '-' }}</text>
              </uni-forms-item>

              <uni-forms-item label="其他:" :key="index">
                <uni-easyinput v-if="boole" v-model="item.threeOther"
                               @blur="blurTable( item,'threeOther')" placeholder="请输入其他"/>
                <text v-else> {{ item.threeOther || '-' }}</text>
              </uni-forms-item>

            </view>

            <view style="display: flex;justify-content: center;align-items: center;"
                  v-if="Number(detailForm.accidentType) === 3 && boole">
              <button class="uni-button add-button" size="mini" type="primary" @click="addThreeLoss">
                添加
              </button>
            </view>

            <uni-forms-item label="上传附件:">
              <image-common :disabled="!boole" :up-type="2" v-model="detailForm.maintenanceProjectUrl"/>
            </uni-forms-item>

          </uni-forms>
        </view>
      </view>

      <!-- 其他费用 -->
      <other-expenses v-model="detailForm" v-if="Number(detailForm.maintenanceType) !== 2" :boole="boole"/>

      <!--出险相关信息-->
      <be-danger-info v-model="detailForm" v-if="Number(detailForm.maintenanceType) !== 2" :boole="boole"
                      :options="options"
                      ref="refDeDangerInfo"/>

      <!--收取加速折旧费-->
      <accelerated v-model="detailForm" v-if="Number(detailForm.maintenanceType) === 3"
                   :depreciationList="depreciationList"
                   :boole="boole"/>

      <!--用印文件-->
      <printed-document v-model="detailForm" v-if="Number(detailForm.maintenanceType) === 3" :boole="boole"/>

      <!--审批流程-->
      <exam-flow v-if="flowId" :instanceId="flowId"/>
    </view>

    <view class="button-container" v-if="boole">
      <button class="btn-item" @click="submit">提 交</button>
    </view>

  </view>
</template>

<script>
import {
  getFindCarWorkOrderInfoVo,
  addMaintenance,
  getMaintenance,
} from "@/api/repair";
import {getInsuranceSelectList, getList} from "@/api/maintain/maintainList";
import basicInfo from "./components/basicInfo.vue"; //基础信息
import repairInfo from "./components/repairInfo.vue"; //维修信息
import insuranceAmount from "./components/insuranceAmount.vue"; //保险公司定损额（车）
import masterCar from "./components/masterCar"; //主车定损
import beDangerInfo from "./components/beDangerInfo.vue"; //出险相关信息
import otherExpenses from "./components/otherExpenses.vue"; //其他费用
import accelerated from "./components/accelerated"; //收取加速折旧费
import printedDocument from "./components/printedDocument"; //用印文件
import {toNumberAdd, toNumberRide} from "@/pages/quota/libs/utils.js";

export default {
  name: "add",
  components: {
    basicInfo,
    repairInfo,
    insuranceAmount,
    masterCar,
    beDangerInfo,
    otherExpenses,
    accelerated,
    printedDocument,
  },
  computed: {
    requiredTable() {
      return function (zrVal, sgVal) {
        let bool = false;
        if (Number(zrVal) !== 1 && Number(sgVal) === 2 && this.boole) {
          bool = true;
        } else {
          bool = false;
        }
        return bool;
      };
    },
    handleValue() {
      return function (val) {
        switch (val) {
          case "1":
            return "报废";
          case "2":
            return "一般维修";
          case "3":
            return "出险";
          default:
            return "-";
        }
      };
    },
  },
  watch: {},
  data() {
    return {
      detailForm: {
        maintenanceId: "",
        carId: "",
        travelMeligile: "",
        workId: "",
        expectStartTime: "",
        expectEndTime: "",
        maintenanceType: "1",
        // 一般维修字段
        maintenanceShop: "",
        faultPhenomenon: "",
        maintenanceFaultDiagnosis: "",
        maintenanceQuoter: 0,
        reasonForClaim: "",
        claimantReason: "",
        swappingAccessories: "",
        comprehensiveRecommendations: "",
        generalMaintenanceRemark: "",
        carMaintenanceProjectList: [],
        maintenanceProjectUrl: "",

        // 报废/出险
        insuredName: "",
        driverName: "",
        responsibleUnitName: "",
        responsibilityType: "",
        responsibleInsuranceUnitName: "",
        accidentDate: "",
        accidentType: "",
        accidentLocation: "",
        humanInjury: "",
        reportingCaseTime: "",
        lossAssessmentUrl: "",
        reportingCaseNum: "",

        vehicleAssessmentPrice: "",
        carOther: "",
        residualValue: "",
        residualUrl: "",
        assessmentTotalPrice: "",
        auctionCompanyName: "",
        bankAccount: "",
        threeLossAssessmentDtoList: [
          {
            personPrice: "",
            rescueCost: "",
            damagePrice: "",
            otherAssessmentPrice: "",
            otherCarNo: "",
            threeOther: "",
          },
        ],

        otherPrice: "",
        otherCostReason: "",
        otherCostUrl: "",

        advancePayment: "",
        advancePaymentCost: "",
        dangerMaintenanceShop: "",
        assessmentRemark: "",

        settlementType: "",
        accidentTime: "",
        compulsoryPolicyNum: "",
        commercialPolicyNum: "",
        depreciationPrice: "",
        depreciationPlan: "",
        useSealsOss: "",
        lossAssessmentOss: "",
        otherAssessmentPrice: "",
        persionAssessmentPrice: "",
        accidentPhotos: "",
        compensationPaymentDto: [
          {
            payee: "", //收款方
            payAmount: "", //   收款费用
            collectionAccount: "", //收账号
          },
        ],
        compensationPaymentTotalAmount: "",
        actualStartTime: "",
        addAmountNun: "",
        actualEndTime: "",
        newPurchasePrice: "",
        accidentsNumber: "",
        chargingFees: "",
        fullCollectionFlag: "",
        insurancePayment: "",
        payType: "",
        maintenanceCompleteUrl: "",
        maintenanceCertificate: "",
        maintenanceFeedback: "",
      },
      boole: false,
      flowId: null,
      options: [],
      detailTitle: "",
      depreciationList: [],
    };
  },
  onLoad(op) {
    let title = "";
    this.flowId = op?.flowId;
    this.detailForm.carId = op?.carId;
    this.detailForm.workId = op?.id;
    if (op?.type === "edit") {
      this.handleGetFindCarWorkOrderInfoVo(op?.id);
      this.boole = true;
      if (op.businessDataId && op.businessDataId !== 'null') {
        this.getMaintenance(op?.businessDataId, op);
      }
      title = `新增维修工单`;
    }
    if (op?.type === "view") {
      this.getMaintenance(op?.businessDataId, op);
      this.boole = false;
      title = `维修工单详情`;
    }
    this.detailForm.carId = op?.carId;
    uni.setNavigationBarTitle({
      title,
    });
  },
  created() {
  },
  mounted() {
    this.handleList();
    this.handleDepreciationPlan();
    this.handleCount(this.detailForm.carMaintenanceProjectList);
  },
  methods: {
    handleDepreciationPlan() {
      getList().then((res) => {
        if (res.code === 200) {
          this.depreciationList = res.data || [];
        }
      });
    },

    handleList() {
      getInsuranceSelectList({businessTypeCode: "4"}).then((res) => {
        if (res.code === 200) {
          this.options = res.data;
        }
      });
    },

    // 处理回显
    handleGetFindCarWorkOrderInfoVo(id) {
      getFindCarWorkOrderInfoVo(id).then((res) => {
        if (res.code === 200) {
          for (let key in res.data) {
            this.$set(this.detailForm, key, res.data[key]);
          }
        }
      });
    },

    // 详情回显
    getMaintenance(id, op) {
      if (!id) return
      getMaintenance(id).then((res) => {
        if (res.code === 200) {
          this.detailForm = res.data;
          this.detailForm.workId = op?.id;
          this.detailForm.businessDataId = op?.businessDataId;
        }
      });
    },

    blurTable(row, field) {
      let _value;
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (field === 'maintNum') {
        msg = /^(?:[1-9]\d*|-(?!0)\d+)$/
      }
      if (row[field]) {
        if (msg.test(Number(row[field]))) {
          if (Number(row[field]) >= 0) {
            _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
            row[field] = _value;
          } else {
            row[field] = "";
          }
        } else {
          row[field] = "";
        }
      }
      this.handleCount(this.detailForm.carMaintenanceProjectList);
    },

    clear(row, field) {
      row[field] = ''
      this.handleCount(this.detailForm.carMaintenanceProjectList);
    },

    //新增维修项目明细
    addDecoration() {
      let obj = {
        maintenanceName: "",
        price: "",
        materialCost: "",
        laborCost: "",
        partNumber: "",
        maintBrand: "",
        maintModel: "",
        maintNum: "",

        detailedInfo: "",
        disabled: true,
      };
      this.detailForm.carMaintenanceProjectList.push(obj);
    },

    //删除维修项目明细
    delDecoration(row, key) {
      this.detailForm.carMaintenanceProjectList.splice(key, 1);
      this.handleCount(this.detailForm.carMaintenanceProjectList);
    },

    handleCount(val) {
      let num = 0,
          total = 0;
      for (let item of val) {
        num = (Number(item.price) * 100).toFixed(0);
        total += Number(num);
      }
      this.$set(this.detailForm, "maintenanceQuoter", (total / 100).toFixed(2));
      console.log(this.detailForm.maintenanceQuoter);
    },

    handlePice(val, index) {
      let num = 0;
      num = toNumberAdd(
          toNumberRide(Number(val.materialCost || 0), Number(val.maintNum || 0)),
          Number(val.laborCost || 0)
      );
      this.$set(this.detailForm.carMaintenanceProjectList[index], "price", num);
      return num;
    },

    //新增保险公司定损额（三者）
    addThreeLoss() {
      let obj = {
        personPrice: "",
        rescueCost: "",
        damagePrice: "",
        otherAssessmentPrice: "",
        otherCarNo: "",
        threeOther: "",
      };
      this.detailForm.threeLossAssessmentDtoList.push(obj);
    },

    //三者删除
    delThreeLoss(row, key) {
      this.detailForm.threeLossAssessmentDtoList.splice(key, 1);
    },

    async submit() {
      try {
        let effectPromises = [
          this.$refs.refBasicInfo.handleEffect(), //基础信息
          this.$refs.refRepairInfo?.handleEffect() || [], //维修信息
          this.$refs.refInsuranceAmount?.handleEffect() || [], //保险公司定损额（车）
          this.$refs.refMasterCar?.handleEffect() || [], //主车定损
          this.handleEffect(), //保险公司定损额（三者）
          this.$refs.refDeDangerInfo?.handleEffect() || [], //出险相关信息
        ];

        await Promise.all(effectPromises);

        // 显示加载状态
        uni.showLoading();

        const res = await addMaintenance(this.detailForm);

        if (res.code === 200) {
          uni.$emit("refBackList", true);
          this.$modal.msgSuccess("提交成功");
          setTimeout(() => {
            this.$tab.navigateBack();
          }, 1000);
        }
      } catch (error) {
        if (typeof error === "string") {
          this.$nextTick(() => {
            uni.pageScrollTo({
              selector: error,
            });
          });
        } else {
          console.error(error);
        }
      } finally {
        setTimeout(() => {
          uni.hideLoading();
        }, 1000)
      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm
            .validate()
            .then((res) => {
              resolve();
              console.log(res);
            })
            .catch((err) => {
              console.log(err, "--err--");
              let key = ".flex-col" + ">>>" + "." + err[0].key;
              reject(key);
            });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.add-button {
  margin-left: 20rpx;
}
</style>


